package br.com.lazyprogrammer.worldsoccermanager.util;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.util.Log;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class BitmapCache {

	private static final int CACHE_MAX_SIZE = 8152;

	private static LruCache<String, Bitmap> cache;
	
	private static Map<String,Double> keys;

	private static int cacheCount;

	private static long memoryUsed;

	private static long maxMemory;
	
	public static void removeBitmap(String key) {
		cache.remove(key);
	}

	public static void addBitmap(String key, Bitmap bitmap) {
		if (cache == null) {
			instanciate();
		}
		if (cache.get(key) == null && bitmap != null) {
			try {
				double bitmapSize = bitmap.getByteCount() / 1024;
				
				while ((memoryUsed + bitmapSize > maxMemory && cacheCount > 0)
						|| cacheCount >= CACHE_MAX_SIZE) {
					removeLastBitmap();
				}
		
				if (memoryUsed + bitmapSize < maxMemory) {
					addBitmapInCache(key, bitmap);
				}
			} catch (Exception e) {
				
			}
		}

	}
	
	public static Bitmap getBitmap(String key) {
		if (key == null) {
			return null;
		}
		if (cache == null) {
			instanciate();
		}
		return cache.get(key);
	}

	private static void addBitmapInCache(String key, Bitmap bitmap) {
		double bitmapSize = bitmap.getByteCount() / 1024;
		cache.put(key, bitmap);
		keys.put(key, bitmapSize);
		
		
		memoryUsed += bitmapSize;
		cacheCount++;
		
		Log.i(BitmapCache.class.getName(), "Adding \"" + key + "\" in Cache, Memory Used:"+memoryUsed+"kb - "+cacheCount + " images");
	}

	private static void removeLastBitmap() {
		cache.trimToSize(cacheCount--);
		
		Set<String> keySet = keys.keySet();
		for (String key : keySet) {
			if (cache.get(key) == null) {
				double size = keys.get(key);
				memoryUsed -= size;
				keys.remove(key);
				break;
			}
		}
		Log.i("beats", "Removing oldest Cache Bitmap, Memory Used:"+memoryUsed+"kb");
	}

	private static void instanciate() {
		cache = new LruCache<String, Bitmap>(CACHE_MAX_SIZE);
		keys = new HashMap<String,Double>();
		
		long maxMemory = Runtime.getRuntime().maxMemory();
		maxMemory = maxMemory / 1024;

		BitmapCache.maxMemory = maxMemory / 8;

		memoryUsed = 0;
		cacheCount = 0;
	}
}
